package com.walkline.screen;

import java.util.Hashtable;
import java.util.Vector;

import localization.WeiboSDKResource;
import net.rim.device.api.command.Command;
import net.rim.device.api.command.CommandHandler;
import net.rim.device.api.command.ReadOnlyCommandMetadata;
import net.rim.device.api.i18n.ResourceBundle;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.system.Display;
import net.rim.device.api.system.RealtimeClockListener;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.FontFamily;
import net.rim.device.api.ui.FontManager;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.image.Image;
import net.rim.device.api.ui.image.ImageFactory;
import net.rim.device.api.ui.menu.CommandItem;
import net.rim.device.api.ui.menu.CommandItemProvider;
import net.rim.device.api.ui.menu.DefaultContextMenuProvider;
import net.rim.device.api.ui.menu.SubMenu;
import net.rim.device.api.util.StringProvider;

import com.walkline.app.WeiboAppConfig;
import com.walkline.util.Enumerations.MenuType;
import com.walkline.util.Enumerations.RefreshAction;
import com.walkline.util.Enumerations.RefreshRemindDelay;
import com.walkline.util.Enumerations.StatusCount;
import com.walkline.util.Function;
import com.walkline.util.container.ForegroundManager;
import com.walkline.util.container.MainMenuListStyleButtonSet;
import com.walkline.util.ui.ListStyleButtonField;
import com.walkline.util.ui.MainMenuListStyleButtonField;
import com.walkline.weibo.BasicAsyncCallback;
import com.walkline.weibo.WeiboException;
import com.walkline.weibo.WeiboSDK;
import com.walkline.weibo.inf.Account;
import com.walkline.weibo.inf.GroupListWrapper;
import com.walkline.weibo.inf.Remind;

public class WeiboScreen extends MainScreen implements WeiboSDKResource, RealtimeClockListener
{
	private static ResourceBundle _bundle = ResourceBundle.getBundle(BUNDLE_ID, BUNDLE_NAME);

	private ForegroundManager _foreground = new ForegroundManager(0);
	private MainMenuListStyleButtonSet _listSet = new MainMenuListStyleButtonSet();
	private MainMenuListStyleButtonField _itemPublic;
	private MainMenuListStyleButtonField _itemGroup;
	private MainMenuListStyleButtonField _itemFriends;
	private MainMenuListStyleButtonField _itemMessage;
	private MainMenuListStyleButtonField _itemMyself;
	//private MainMenuListStyleButtonField _itemSettings;
	//private Remind _reminds;

	private WeiboSDK _weibo;
	private WeiboAppConfig _appConfig;

	private LabelField labelTitleField;

//	private ItemProvider itemProvider = new ItemProvider();
	private GroupListWrapper _groupListWrapper;

	private String _page_count = "20";
	private String _current_page = "1";
	private String _max_id = "0";
	private int _refresh_remind_delay = 0;
	private static int _clockUpdateCount = 0;

	public WeiboScreen(WeiboSDK weibo)
	{
		super(NO_VERTICAL_SCROLL | USE_ALL_HEIGHT | NO_SYSTEM_MENU_ITEMS);

		setContextMenuProvider(new DefaultContextMenuProvider());
		setDefaultClose(false);

		try {
			FontFamily family = FontFamily.forName("BBGlobal Sans");
			Font appFont = family.getFont(Font.PLAIN, 8, Ui.UNITS_pt);
			FontManager.getInstance().setApplicationFont(appFont);
		} catch (ClassNotFoundException e) {}

		_weibo = weibo;
		_appConfig = weibo.getAppConfig();
		_page_count = StatusCount.choicesStatusCount[_appConfig.getStatusCount()];
		_refresh_remind_delay = RefreshRemindDelay.choicesRefreshDelayValue[_appConfig.getRemindDelay()];
 
		String titleIconName = Display.getWidth() < 640 ? "titleIcon_small.png" : "titleIcon_large.png";
		BitmapField bmpTitleField = new BitmapField(Bitmap.getBitmapResource(titleIconName));
		bmpTitleField.setSpace(5, 5);
		labelTitleField = new LabelField(WeiboAppConfig.APP_TITLE, LabelField.ELLIPSIS);
		labelTitleField.setFont(WeiboAppConfig.FONT_MAIN_TITLE);

		HorizontalFieldManager hfm = new HorizontalFieldManager(USE_ALL_WIDTH);
		VerticalFieldManager vfm = new VerticalFieldManager(FIELD_VCENTER);
		vfm.add(labelTitleField);
		hfm.add(bmpTitleField);
		hfm.add(vfm);
		hfm.setBackground(WeiboAppConfig.bgColor_Gradient);
		setTitle(hfm);

		createUI();

		add(_foreground);

		UiApplication.getUiApplication().addRealtimeClockListener(this);

		UiApplication.getUiApplication().invokeLater(new Runnable()
		{
			public void run()
			{
				//如果获取用户id成功，说明用户授权没有问题，这时候再去进行后续初始化设置
				_weibo.getAccount(new GetAccountCallback(), null);
			}
		});
	}

	private void createUI()
	{
		//"最新微博"
		_itemPublic = new MainMenuListStyleButtonField(MenuType.PUBLIC);
		_itemPublic.setChangeListener(new FieldChangeListener()
		{
			public void fieldChanged(Field field, int context)
			{
				Hashtable params = new Hashtable();

				params.put("title", _itemPublic.getMenuTitle());
				params.put("count", _page_count);

				UiApplication.getUiApplication().pushScreen(new ShowStatusesMainScreen(_weibo, params, RefreshAction.PUBLICTIMELINE));
			}
		});
		_itemPublic.setEnabled(false);
		_listSet.add(_itemPublic);

		//好友微博
		_itemFriends = new MainMenuListStyleButtonField(MenuType.FRIEND);
		_itemFriends.setChangeListener(new FieldChangeListener()
		{
			public void fieldChanged(Field field, int context)
			{
				Hashtable params = new Hashtable();

				params.put("title", _itemFriends.getMenuTitle());
				params.put("count", _page_count);
				params.put("page", _current_page);
				params.put("max_id", _max_id);

				UiApplication.getUiApplication().pushScreen(new ShowStatusesMainScreen(_weibo, params, RefreshAction.FRIENDSTIMELINE));
			}
		});
		_itemFriends.setEnabled(false);
		_listSet.add(_itemFriends);

		//"分组"
		_itemGroup = new MainMenuListStyleButtonField(MenuType.GROUP);
		_itemGroup.setChangeListener(new FieldChangeListener()
		{
			public void fieldChanged(Field field, int context)
			{
				UiApplication.getUiApplication().pushScreen(new ShowGroupListsMainScreen(_weibo, _groupListWrapper));
			}
		});
		_itemGroup.setEnabled(false);
		_listSet.add(_itemGroup);

		//"消息"
		_itemMessage = new MainMenuListStyleButtonField(MenuType.MESSAGE);
		_itemMessage.setChangeListener(new FieldChangeListener()
		{
			public void fieldChanged(Field field, int context)
			{
				UiApplication.getUiApplication().pushScreen(new MessageBoxMainScreen(_weibo));
			}
		});
		_itemMessage.setEnabled(false);
		_listSet.add(_itemMessage);

		//"我"
		_itemMyself = new MainMenuListStyleButtonField(MenuType.MYSELF);
		_itemMyself.setChangeListener(new FieldChangeListener()
		{
			public void fieldChanged(Field field, int context)
			{
				Hashtable params = new Hashtable();

				params.put("uid", _weibo.getUserIdStr());
				params.put("screen_name", "");

				UiApplication.getUiApplication().pushScreen(new HomePageMainScreen(_weibo, params));
			}
		});
		_itemMyself.setEnabled(false);
		_listSet.add(_itemMyself);

		/*
		//"设置"
		_itemSettings = new MainMenuListStyleButtonField(MenuType.SETTINGS);
		_itemSettings.setChangeListener(new FieldChangeListener()
		{
			public void fieldChanged(Field field, int context)
			{
				UiApplication.getUiApplication().pushScreen(new ShowSettingsMainScreen(_weibo));
			}
		});
		_listSet.add(_itemSettings);
		*/

		_foreground.add(_listSet);
	}

    MenuItem menuRefreshMessage = new MenuItem(_bundle, MENU_REFRESH_MESSAGE, 100, 10)
    {
    	public void run() {refreshRemind();}
    };

    MenuItem menuNewStatus = new MenuItem(_bundle, MENU_NEW_STATUS, 100, 20)
    {
    	public void run() {createNewStatus();}
    };

    MenuItem menuSearch = new MenuItem(_bundle, MENU_SEARCH, 100, 40)
    {
    	public void run() {}
    };

    MenuItem menuSettings = new MenuItem(_bundle, MENU_SETTINGS, 100, 50)
    {
    	public void run() {showSettingsScreen();}
    };

    MenuItem menuAbout = new MenuItem(_bundle, MENU_ABOUT, 100, 60)
    {
    	public void run() {showAboutScreen();}
    };

    MenuItem menuExit = new MenuItem(_bundle, MENU_EXIT, 100, 80)
    {
    	public void run() {Function.showExitDialog();}
    };

    MenuItem menuToolsRefreshToken = new MenuItem(_bundle, MENU_LOGIN_AGAIN, 200, 10)
    {
    	public void run()
    	{
    		try {
    			_weibo.refreshAccessToken();
    		} catch (WeiboException e) {}
    	}
    };

    MenuItem menuToolsRevoke = new MenuItem(_bundle, MENU_REVOKE, 200, 20)
    {
    	public void run() 
    	{
    		if (_weibo.SignOut())
    		{
    			Function.errorDialog("当前用户已注销，程序即将关闭，要继续使用请重新登录。");

    			_appConfig.setUsername("");
    			_appConfig.setPassword("");
    			_appConfig.clean();
    			System.exit(0);
    		} else {
    			Function.errorDialog("无法注销当前用户");
    		}
    	}
    };

    protected void makeMenu(Menu menu, int instance)
    {
    	SubMenu menuTools = new SubMenu(null, _bundle, MENU_TOOLS, 100, 45);
    	menuTools.add(menuToolsRefreshToken);
    	menuTools.addSeparator();
    	menuTools.add(menuToolsRevoke);

    	menu.add(menuRefreshMessage);
    	menu.addSeparator();
    	menu.add(menuNewStatus);
    	menu.addSeparator();
    	menu.add(menuTools);
    	menu.add(menuSettings);
    	menu.addSeparator();
    	menu.add(menuAbout);
    	menu.addSeparator();
    	menu.add(menuExit);

    	super.makeMenu(menu, instance);
    }

    public boolean onClose()
    {
    	UiApplication.getUiApplication().requestBackground();

    	return true;
    }

    protected boolean keyChar(char character, int status, int time)
    {
    	switch (character)
    	{
    		case Characters.LATIN_CAPITAL_LETTER_C:
    		case Characters.LATIN_SMALL_LETTER_C:
    			createNewStatus();
    			return true;
			case Characters.LATIN_CAPITAL_LETTER_R:
			case Characters.LATIN_SMALL_LETTER_R:
				refreshRemind();
				return true;
			case Characters.LATIN_CAPITAL_LETTER_A:
			case Characters.LATIN_SMALL_LETTER_A:
				showAboutScreen();
				return true;
			case Characters.LATIN_CAPITAL_LETTER_O:
			case Characters.LATIN_SMALL_LETTER_O:
				showSettingsScreen();
				return true;
			case Characters.LATIN_CAPITAL_LETTER_Q:
			case Characters.LATIN_SMALL_LETTER_Q:
				Function.showExitDialog();
				return true;
		}

    	return super.keyChar(character, status, time);
    }

    private void createNewStatus()
    {
    	UiApplication.getUiApplication().pushScreen(new NewStatusMainScreen(_weibo));
    }

	private void showSettingsScreen()
	{
		UiApplication.getUiApplication().pushScreen(new ShowSettingsMainScreen(_weibo));
	}

	private void showAboutScreen()
	{
		UiApplication.getUiApplication().pushScreen(new ShowAboutMainScreen());
	}

	protected void onExposed()
	{
		_page_count = StatusCount.choicesStatusCount[_appConfig.getStatusCount()];
		_refresh_remind_delay = RefreshRemindDelay.choicesRefreshDelayValue[_appConfig.getRemindDelay()];

		UiApplication.getUiApplication().invokeLater(new Runnable()
		{
			public void run() {updateReminds();}
		});

		super.onExposed();
	}

	class GetAccountCallback extends BasicAsyncCallback
	{
		public void onComplete(final Account value, Object state)
		{
			if (value != null)
			{
				UiApplication.getUiApplication().invokeLater(new Runnable()
				{
					public void run()
					{
						_weibo.setUserId(value.getUserId());

						_itemPublic.setEnabled(true);

						_weibo.getRemind(new GetRemindCallback(), null);
						_weibo.getGroupList(new GetGroupListCallback(), null);
					}
				});
			}
		}

		public void onException(Exception e, Object state) {Function.errorDialog(e.toString());}
	}

	class GetRemindCallback extends BasicAsyncCallback
	{
		public void onComplete(final Remind value, Object state)
		{
			if (value != null)
			{
				_weibo.setReminds(value);

				UiApplication.getUiApplication().invokeLater(new Runnable()
				{
					public void run() {updateReminds();}
				});
			}
		}

		public void onException(Exception e, Object state) {Function.errorDialog("one problem");} //Function.errorDialog(e.toString());}
	}

	class GetGroupListCallback extends BasicAsyncCallback
	{
		public void onComplete(final GroupListWrapper value, Object state)
		{
			if (value != null)
			{
				_itemGroup.setEnabled(true);
				_groupListWrapper = value;
			}
		}

		public void onException(Exception e, Object state) {Function.errorDialog(e.toString());}
	}

	/**
	 * 刷新消息提醒数量
	 */
	private void refreshRemind()
	{
		RefreshContentsScreen popupScreen = new RefreshContentsScreen(_weibo, new Hashtable(), RefreshAction.REFRESHREMIND);
		UiApplication.getUiApplication().pushModalScreen(popupScreen);

		Remind reminds = popupScreen.getReminds();

		if (popupScreen != null) {popupScreen = null;}
		if (reminds != null) {_weibo.setReminds(reminds); updateReminds();}
	}

	/**
	 * 更新消息提醒数量
	 */
	private void updateReminds()
	{
		_itemPublic.setEnabled(true);
		_itemFriends.setEnabled(true);
		_itemGroup.setEnabled(true);
		_itemMyself.setEnabled(true);
		_itemMessage.setEnabled(true);

		Remind reminds = _weibo.getReminds();

		if (reminds != null)
		{
			_itemFriends.updateUnreadCount(reminds.getStatus());
			_itemMessage.updateUnreadCount(reminds.getAllUnreadCount());
			_itemMyself.updateUnreadCount(reminds.getFollower());			
		}
	}

	private String getResString(int key) {return _bundle.getString(key);}

	class ItemProvider implements CommandItemProvider
	{
        public Object getContext(Field field) {return field;}

        public Vector getItems(Field field)
        {
        	Vector items = new Vector();

        	Image myIcon = ImageFactory.createImage(Bitmap.getBitmapResource("titleIcon_large.png"));
        	Image iconDelete = ImageFactory.createImage(Bitmap.getBitmapResource("delete.png"));
        	Image iconPreview = ImageFactory.createImage(Bitmap.getBitmapResource("preview.png"));
        	Image iconDownload = ImageFactory.createImage(Bitmap.getBitmapResource("download.png"));
        	Image iconMove = ImageFactory.createImage(Bitmap.getBitmapResource("move.png"));
        	Image iconProperty = ImageFactory.createImage(Bitmap.getBitmapResource("property.png"));
        	Image iconShare = ImageFactory.createImage(Bitmap.getBitmapResource("share.png"));
        	Image iconUnShare = ImageFactory.createImage(Bitmap.getBitmapResource("unshare.png"));
        	Image iconRename = ImageFactory.createImage(Bitmap.getBitmapResource("rename.png"));

        	if (field instanceof ListStyleButtonField)
        	{
        		ListStyleButtonField item = (ListStyleButtonField) field;

           		CommandItem cmdDownload = new CommandItem(new StringProvider(getResString(CONTEXTMENU_DOWNLOAD)), iconDownload, new Command(new CommandHandler() {
   					public void execute(ReadOnlyCommandMetadata metadata, Object context) {
   					}
   				}));
           		CommandItem cmdPreview = new CommandItem(new StringProvider(getResString(CONTEXTMENU_PREVIEW)), iconPreview, new Command(new CommandHandler() {
   					public void execute(ReadOnlyCommandMetadata metadata, Object context) {
   					}
   				}));
           		CommandItem cmdShare = new CommandItem(new StringProvider(getResString(CONTEXTMENU_SHARE)), iconShare, new Command(new CommandHandler() {
   					public void execute(ReadOnlyCommandMetadata metadata, Object context) {
   					}
   				}));
           		CommandItem cmdUnshare = new CommandItem(new StringProvider(getResString(CONTEXTMENU_UNSHARE)), iconUnShare, new Command(new CommandHandler() {
   					public void execute(ReadOnlyCommandMetadata metadata, Object context) {
   					}
   				}));
           		CommandItem cmdProperty = new CommandItem(new StringProvider(getResString(CONTEXTMENU_PROPERTY)), iconProperty, new Command(new CommandHandler() {
   					public void execute(ReadOnlyCommandMetadata metadata, Object context) {
   					}
   				}));
           		CommandItem cmdDelete = new CommandItem(new StringProvider(getResString(CONTEXTMENU_DELETE)), iconDelete, new Command(new CommandHandler() {
   					public void execute(ReadOnlyCommandMetadata metadata, Object context) {
   					}
   				}));
           		CommandItem cmdMove = new CommandItem(new StringProvider(getResString(CONTEXTMENU_MOVE)), iconMove, new Command(new CommandHandler() {
   					public void execute(ReadOnlyCommandMetadata metadata, Object context) {
   					}
   				}));
           		CommandItem cmdRename = new CommandItem(new StringProvider(getResString(CONTEXTMENU_RENAME)), iconRename, new Command(new CommandHandler() {
   					public void execute(ReadOnlyCommandMetadata metadata, Object context) {
   					}
   				}));

           		items.addElement(cmdDownload);
           		items.addElement(cmdShare);
           		items.addElement(cmdPreview);
           		items.addElement(cmdUnshare);
           		items.addElement(cmdProperty);
           		items.addElement(cmdDelete);
           		items.addElement(cmdMove);
           		items.addElement(cmdRename);
        	} else if (field instanceof LabelField) {
        		CommandItem cmdDownload = new CommandItem(new StringProvider(getResString(CONTEXTMENU_DOWNLOAD)), iconDownload, new Command(new CommandHandler() {
					public void execute(ReadOnlyCommandMetadata metadata, Object context) {
					}
				}));
        		CommandItem cmdPreview = new CommandItem(new StringProvider(getResString(CONTEXTMENU_PREVIEW)), iconPreview, new Command(new CommandHandler() {
					public void execute(ReadOnlyCommandMetadata metadata, Object context) {
					}
				}));
        		CommandItem cmdShare = new CommandItem(new StringProvider(getResString(CONTEXTMENU_SHARE)), iconShare, new Command(new CommandHandler() {
					public void execute(ReadOnlyCommandMetadata metadata, Object context) {
					}
				}));

        		items.addElement(cmdDownload);
        		items.addElement(cmdPreview);
        		items.addElement(cmdShare);
        	}

    		return items;
        }
	}

	public void clockUpdated()
	{
		_clockUpdateCount += 1;

		if (_clockUpdateCount >= _refresh_remind_delay)
		{
			_clockUpdateCount = 0;
			_weibo.getRemind(new GetRemindCallback(), null);	
		}
	}
}